module(..., package.seeall)
--[[

===========================================================
Author: Osvaldo Ros (osvaldo@splosive.com)

Copyright (C) 2011 by Splosive Labs (www.splosive.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

===========================================================
]]



local Class = require("RDX_Class")
com = require("RDX")


--[[
================================================
Behaviors package 

 	This library contains behaviors that can be used with Splosive's RDX framework.
	
	All behaviors must implement an activate, deactivate and execute methods. A context object will be passed to the behavior with relevant information about the
	current view, the target(s), event source(s) and the environment. 

	The easiest way to get started is by extending the Behavior template.
	It is strongly recommended that you don't modify this file and instead you create your own behaviors file and use the registerBehaviors method in your main.lua
	in order to load your own behaviors like this:

	com = require("RDX")

	config = com.splosive.Config
	config.registerBehaviors("MyBehaviors")

================================================
]]


--[[
	================================================
	templates package
	================================================
	]]
function buildTemplates()

	local BehaviorTemplate = function(context, public, protected)
		
		local super = Class.buildClass(nil, public, protected)
		
		super.public.ACTIVATION_AUTO = "activationAuto"
		super.public.ACTIVATION_PARENT_EXECUTE = "activationParentExecute"
		super.public.ACTIVATION_MANUAL = "activationManual"
		
		super.public.EXECUTION_PARENT_EXECUTE = "executionParentExecute"
		super.public.EXECUTION_MANUAL = "executionManual"
		
		super.public.activated = false
		super.public.parent = nil
		
		super.protected.onExecute = function()
			super.protected.context.descriptor.onExecute()
		end
		
		super.public.preactivate = function()
			--com.splosive.trace("preactivate > ".. super.public.type, "View-Behavior-Template-Preactivate")
			for propName,propValue in pairs(super.protected.context.descriptor) do
				if(type(propValue) == "string" and propName ~= "type" and propName ~= "event" and propName ~= "id" and propName ~= "view"  and propName ~= "eventSource"  and propName ~= "eventSources"  and propName ~= "target"  and propName ~= "targets" )then
					--com.splosive.trace("preactivate > propName = ".. propName .. ", propValue = " .. propValue, "View-Behavior-Template-Preactivate")
					local currentObj = nil
					local StringUtils = com.splosive.StringUtils
					local propParts = StringUtils.split(propValue, ".")
					
					for partName,partValue in pairs(propParts) do
						--com.splosive.trace("preactivate > propName = " .. propName .. ",partValue = ".. partValue, "View-Behavior-Template-Preactivate")
						
						if(currentObj == nil)then
							if(public[partValue] ~= nil)then
								--com.splosive.trace("preactivate > partValue  ".. partValue .. " matches property in public  ", "View-Behavior-Template-Preactivate")
								currentObj = public[partValue]
							elseif(protected[partValue] ~= nil)then
								--com.splosive.trace("preactivate > partValue  ".. partValue .. " matches property in protected  ", "View-Behavior-Template-Preactivate")
								currentObj = protected[partValue]
							end
						else
							if(currentObj[partValue] ~= nil)then
								--com.splosive.trace("preactivate > partValue  ".. partValue .. " matches property in currentObj  ", "View-Behavior-Template-Preactivate")
								currentObj = currentObj[partValue]
							end
						end
					end
					
					if(currentObj ~= nil)then
						--com.splosive.trace("preactivate > assigning currentObj to the descriptor  ", "View-Behavior-Template-Preactivate")
						super.protected.context[propName] = currentObj
					end
					
					
				end
			end
		end
		
		super.public.activate = function()
			--com.splosive.trace("BehaviorTemplate > activate from " .. public.type, "View-Behavior-Template")
			if(super.public.activated == false)then
				if(super.protected.context.actions ~= nil)then
					for k,nestedBehavior in ipairs(super.protected.context.actions) do
						com.splosive.trace("checking nestedBehavior ".. nestedBehavior.type .. " activationPolicy = " .. nestedBehavior.activationPolicy, "View-Behavior-Template")
						nestedBehavior.parent = public			
						if(nestedBehavior.activationPolicy == public.ACTIVATION_AUTO) then
							com.splosive.trace("activating nestedBehavior ".. nestedBehavior.type, "View-Behavior-Template")
							nestedBehavior.preactivate()
							if(nestedBehavior.activated == false)then
								nestedBehavior.activate()
							else
								com.splosive.trace("nestedBehavior ".. nestedBehavior.type .. " is already active", "View-Behavior-Template")
							end
						end
					end
				end
			end
			
			super.public.activated = true
			
		end
		
		super.public.deactivate = function()
			--com.splosive.trace("BehaviorTemplate > deactivate from " .. public.type, "View-Behavior-Template")
			if(super.public.activated == true)then
				if(super.protected.context.actions ~= nil)then
					for k,nestedBehavior in ipairs(super.protected.context.actions) do
						com.splosive.trace("deactivate nestedBehavior ".. nestedBehavior.type, "View-Behavior-Template")
						nestedBehavior.deactivate()
					end
				end
			end
			
			super.public.activated = false
			
		end
		
		super.public.execute = function()
			--com.splosive.trace("BehaviorTemplate > execute from " .. public.type, "View-Behavior-Template")
			
			if(super.protected.context.actions ~= nil)then
				for k,nestedBehavior in ipairs(super.protected.context.actions) do
					com.splosive.trace("checking nestedBehavior ".. nestedBehavior.type .. " executionPolicy = " .. nestedBehavior.executionPolicy, "View-Behavior-Template")
					
					if(nestedBehavior.activationPolicy == public.ACTIVATION_PARENT_EXECUTE) then
						nestedBehavior.preactivate()
						if(nestedBehavior.activated == false)then
							com.splosive.trace("activating nestedBehavior ".. nestedBehavior.type, "View-Behavior-Template")
							nestedBehavior.activate()
						else
							com.splosive.trace("nestedBehavior ".. nestedBehavior.type .. " is already active", "View-Behavior-Template")
						end
						
					end
					
					if(nestedBehavior.executionPolicy == public.EXECUTION_PARENT_EXECUTE) then
						com.splosive.trace("execution nestedBehavior ".. nestedBehavior.type, "View-Behavior-Template")
						nestedBehavior.execute()
					end
					
				end
			end
			
			if(super.protected.context.descriptor.onExecute ~= nil)then
				protected.onExecute()
			end
			
		end
		
		
		super.protected.context = context
		super.public.type = context.descriptor.type
		super.public.activationPolicy = context.descriptor.activationPolicy or public.ACTIVATION_AUTO
		super.public.executionPolicy = context.descriptor.executionPolicy or public.EXECUTION_MANUAL
		
		return super
		
	end
	
	package.BehaviorTemplate = BehaviorTemplate
	
	return package
	
end

templates = buildTemplates()



function splosive()

	local package = {}
	
--[[
	================================================
	utils package: Contains utils behaviors such as timer related stuff
	================================================
	]]
	
	local utils = function()
		
		local package = {}
		
		--[[
		================================================
		TimeElapsed
		================================================
		]]
	
		local TimeElapsed = function(context)
		
			local public = {}
			local protected = {}
			
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			protected.timeLeft = nil
			protected.startTime = nil
			protected.timerId = nil
			
			public.activate = function()
			
				if(this.context.descriptor.target ~= nil)then
					Runtime:addEventListener( "enterFrame", this.onEnterFrame )
					this.startTime = system.getTimer()
					this.timeLeft = this.context.descriptor.time
				else
					this.timerId = timer.performWithDelay( this.context.descriptor.time, public.execute )
				end
				
				super.public.activate()
			end
			
			public.deactivate = function()
				if(this.context.descriptor.target ~= nil)then
					Runtime:removeEventListener( "enterFrame", this.onEnterFrame )
				end
				
				if(this.timerId ~= nil)then
					timer.cancel(this.timerId)
				end
				
				super.public.deactivate()
			end
			
			protected.onEnterFrame = function(event)
				local timeElapsed = system.getTimer() - this.startTime
				this.timeLeft = this.context.descriptor.time - timeElapsed
				
				local displayTime 
				
				if(this.timeLeft < 0)then
					displayTime = "0"
				else
					displayTime = math.ceil(this.timeLeft/1000 )
				end
				
				this.context.target.text = displayTime
				--[[
				]]
				this.context.target:setReferencePoint(display.CenterReferencePoint);
				this.context.target.x = this.context.target.descriptor.x
				this.context.target.y = this.context.target.descriptor.y
				
				
				if(this.timeLeft <= 0)then
					public.execute()
					public.deactivate()
				end
			end
			
			public.execute = function()
				super.public.execute()
			end
			
			
			return api
			
		end
		
		package.TimeElapsed = TimeElapsed
		
		return package
	
	end
	
	--[[
	================================================
	Physics package: Contains behaviors associated with phycis simulations
	================================================
	]]
	
	local physics = function()
		
		local package = {}
		
			--[[
		================================================
		Pause
		================================================
		]]
	
		local Pause = function(context)
		
			local public = {}
			local protected = {}
			
			local physics = require("physics")
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.execute = function()
				com.splosive.PhysicsState.pause()
				super.public.execute()
			end
			
			
			return api
			
		end
		
		--[[
		================================================
		Resume
		================================================
		]]
	
		local Resume = function(context)
		
			local public = {}
			local protected = {}
			
			local physics = require("physics")
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.execute = function()
				com.splosive.PhysicsState.start()
				super.public.execute()
			end
			
			
			return api
			
		end
		
			--[[
		================================================
		ObjectSleepTrigger
		================================================
		]]
	
		local ObjectSleepTrigger = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.CALCULATION_QUICK = "quick"
			public.CALCULATION_PRECISE = "precise"
			
			protected.bodyCoordinates = nil
			protected.singleCoordinates = nil
			
			
			public.calculationMode = public.CALCULATION_QUICK
			public.quickCycles = 10
			public.currentCycle = 0
			
			public.activate = function()
			
				this.bodyCoordinates = nil
				this.singleCoordinates = nil
			
				if(this.context.descriptor.targetCondition == nil)then
					this.context.descriptor.targetCondition = "AND"
				end
				
				public.calculationMode = this.context.descriptor.calculationMode or public.CALCULATION_QUICK
				
				Runtime:addEventListener( "enterFrame", this.onEnterFrame )
				super.public.activate()
			end
			
			public.deactivate = function()
				Runtime:removeEventListener( "enterFrame", this.onEnterFrame )
				super.public.deactivate()
			end
			
			protected.onEnterFrame = function( event )
			
				if(com.splosive.PhysicsState.physicsRunning == false)then
					return
				end
			
				if(public.calculationMode == public.CALCULATION_QUICK)then
					this.evaluateSleepQuickly()
				elseif(public.calculationMode == public.CALCULATION_PRECISE)then
					this.evaluateSleepPrecisely()
				end
			end
			
			
			protected.evaluateSleepQuickly = function()
			
				-- If it's only one target execute as soon as it falls asleep
				if(this.context.target ~= nil)then
					
					if(this.singleCoordinates)then
				
						if(math.floor(this.context.target.x) == this.singleCoordinates.x and math.floor(this.context.target.y) == this.singleCoordinates.y)then
							
							if(public.currentCycle >= public.quickCycles)then
								com.splosive.trace("ObjectSleepTrigger > The given object is sleep, execute trigger", "View-Behavior-ObjectSleepTrigger")
								public.execute()
							end
							
							public.currentCycle = public.currentCycle + 1
						else
							public.currentCycle = 0
						end
					
					end
					
					this.singleCoordinates = {x = math.floor(this.context.target.x), y = math.floor(this.context.target.y)}
					
				-- If there are multiple targets check the targetCondition to see if we are checking for all or at least one
				elseif(this.context.targets ~= nil)then
				
					if(this.bodyCoordinates)then
				
						if(this.context.descriptor.targetCondition == "AND")then
						
							local allSleep = true
							for andK,andCurrentTarget in ipairs(this.context.targets) do
								local currentCoordinates = this.bodyCoordinates[andCurrentTarget.id]
								if(math.floor(andCurrentTarget.x) == currentCoordinates.x and math.floor(andCurrentTarget.y) == currentCoordinates.y)then
								else
									allSleep = false
								end				
							end
							
							if(allSleep)then
								if(public.currentCycle >= public.quickCycles)then
									com.splosive.trace("ObjectSleepTrigger > All objects are sleep, execute trigger", "View-Behavior-ObjectSleepTrigger")
									public.execute()
								end
								
								public.currentCycle = public.currentCycle + 1
							else
								public.currentCycle = 0
							end
							
						elseif(this.context.descriptor.targetCondition == "OR")then
							for orK,orCurrentTarget in ipairs(this.context.targets) do
								local currentCoordinates = this.bodyCoordinates[orCurrentTarget.id]
								local atLeastOneSleep = false
								if(math.floor(orCurrentTarget.x) == currentCoordinates.x and math.floor(orCurrentTarget.y) == currentCoordinates.y)then
									atLeastOneSleep = true
								end				
							end
							
							if(atLeastOneSleep)then
								if(public.currentCycle >= public.quickCycles)then
									com.splosive.trace("ObjectSleepTrigger > at least one object is sleep, execute trigger", "View-Behavior-ObjectSleepTrigger")
									public.execute()
								end
								
								public.currentCycle = public.currentCycle + 1
							else
								public.currentCycle = 0
							end
						end
					
					end
					
					this.bodyCoordinates = {}
					for evalK,evalCurrentTarget in ipairs(this.context.targets) do
						this.bodyCoordinates[evalCurrentTarget.id] = {x = math.floor(evalCurrentTarget.x), y = math.floor(evalCurrentTarget.y)}
					end
					
					
					
				end
				
			end
			
			protected.evaluateSleepPrecisely = function()
			
				-- If it's only one target execute as soon as it falls asleep
				if(this.context.target ~= nil)then
					if(this.context.target.isAwake == false) then
						com.splosive.trace("ObjectSleepTrigger > The given object is sleep, execute trigger", "View-Behavior-ObjectSleepTrigger")
						public.execute()
					end
					
				-- If there are multiple targets check the targetCondition to see if we are checking for all or at least one
				elseif(this.context.targets ~= nil)then
				
					if(this.context.descriptor.targetCondition == "AND")then
					
						local allSleep = true
						for andK,andCurrentTarget in ipairs(this.context.targets) do
							if(andCurrentTarget.isAwake) then
								allSleep = false
							end				
						end
						
						if(allSleep)then
							com.splosive.trace("ObjectSleepTrigger > All objects are sleep, execute trigger", "View-Behavior-ObjectSleepTrigger")
							public.execute()
						end
						
					elseif(this.context.descriptor.targetCondition == "OR")then
						for orK,orCurrentTarget in ipairs(this.context.targets) do
							
							local atLeastOneSleep = false
							if(orCurrentTarget.isAwake == false) then
								atLeastOneSleep = true
							end				
						end
						
						if(atLeastOneSleep)then
							com.splosive.trace("ObjectSleepTrigger > at least one object is sleep, execute trigger", "View-Behavior-ObjectSleepTrigger")
							public.execute()
						end
					end
					
				end
				
			end
			
			public.execute = function()
				com.splosive.trace("ObjectSleepTrigger > execute" , "View-Behavior-ObjectSleepTrigger")
				Runtime:removeEventListener( "enterFrame", this.onEnterFrame )
				super.public.execute()
			end
			
			
			return api
			
		end
	
		--[[
		================================================
		SlingshotThrow 
		================================================
		]]
	
		local SlingshotThrow = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			this.xForce = 0
			this.yForce = 0
			
			public.activate = function()
			
				this.xForce = this.context.descriptor.xForce or 0
				this.yForce = this.context.descriptor.yForce or 0
			
				if(this.context.event == "OBJECT_PRESS")then
					--this.context.eventSource.touch = this.objectPressed
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				
				super.public.activate()
			end
			
			public.deactivate = function()
				--this.context.eventSource.touch = nil
				this.context.eventSource:removeEventListener( "touch", this.objectPressed )
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					Runtime:addEventListener( "touch", this.onScreenTouch )
					return true
				end
			end
			
			protected.onScreenTouch = function(event)
				if(event.phase == "ended") then
				
					local x, y = this.context.target.parent:contentToLocal(event.x, event.y)
					
					this.xForce = (-1 * (x - this.context.target.x)) * 15	--> 2.75
					this.yForce = (-1 * (y - this.context.target.y)) * 15	--> 2.75
						
					public.execute()
					Runtime:removeEventListener( "touch", this.onScreenTouch )
					return true
				else
				
					local x, y = this.context.target.parent:contentToLocal(event.x, event.y)
					
					this.xForce = (-1 * (x - this.context.target.x)) * 2.15	--> 2.75
					this.yForce = (-1 * (y - this.context.target.y)) * 2.15	--> 2.75
				
					--com.splosive.trace("xForce = " .. xForce ..", yForce = " .. yForce , "View-Behavior-SlingshotThrow")
				end
			end
			
			
			public.execute = function()
				this.context.target:applyForce( this.xForce, this.yForce, this.context.target.x, this.context.target.y )
				super.public.execute()
			end
			
			return api
			
		end
		
		--[[
		================================================
		DragThrow 
		================================================
		]]
	
		local DragThrow = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.FORCE_BY_DISTANCE = "forceByDistance"
			public.FIXED_BY_ANGLE = "fixedByAngle"
			
			public.forceMode = FIXED_BY_ANGLE
			
			this.xForce = 0
			this.yForce = 0
			
			this.startX = 0
			this.startY = 0
			this.maxForce = 1500
			this.touchBuffer = 0
			this.pressedEventSource = false
			this.executionLimit = nil
			this.executionNumber = 0
			this.fixedForceRadius = nil
			
			protected.mCeil = math.ceil
			protected.mAtan2 = math.atan2
			protected.cos = math.cos
			protected.sin = math.sin
			protected.rad = math.rad
			protected.mPi = math.pi
			protected.mSqrt = math.sqrt
			protected.object = nil
			protected.parentContainer = nil
			
			protected.showDistanceVector = nil
			protected.distanceVector = nil
			
			protected.minAngle = nil
			protected.maxAngle = nil
			
			public.activate = function()
				com.splosive.trace("DragThrow activate!", "View-Behavior-DragThrow")
				this.executionNumber = 0
				
				this.showDistanceVector = this.context.descriptor.showDistanceVector or true
				this.minAngle = this.context.descriptor.minAngle or -360
				this.maxAngle = this.context.descriptor.maxAngle or 360
				this.fixedForceRadius = this.context.descriptor.fixedForceRadius or 120
				public.forceMode = this.context.descriptor.forceMode or public.FIXED_BY_ANGLE
				this.xForce = this.context.descriptor.xForce or 0
				this.yForce = this.context.descriptor.yForce or 0
				this.touchBuffer = this.context.descriptor.touchBuffer or 0
				this.executionLimit = this.context.descriptor.executionLimit
				
				if(public.forceMode == public.FIXED_BY_ANGLE)then
					this.showDistanceVector = false
				end
				
				if(this.context.descriptor.pointerAsset ~= nil)then
					this.parentContainer = this.context.target.parent
					
					if(this.object == nil)then
						this.object = display.newImage( this.context.descriptor.pointerAsset )
						this.object.isVisible = false
						
						this.parentContainer:insert( this.object )
					end
					
					this.context.target:toFront()
					
				end
				
				if(this.context.eventSource == Runtime)then
					error("Runtime is not a valid eventSource for DragThrow behavior ")
				end
			
				if(this.context.event == "OBJECT_PRESS")then
					--this.context.eventSource:addEventListener( "touch", this.objectPressed )
					Runtime:addEventListener( "touch", this.objectPressed )
				end
				
				super.public.activate()
			end
			
			public.deactivate = function()
			
				if(this.object ~= nil)then
					this.object:removeSelf()
					this.object = nil
				end
			
			 	--this.context.eventSource:removeEventListener( "touch", this.objectPressed )
			 	Runtime:removeEventListener( "touch", this.objectPressed )
			 	super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
			
				local left = (this.context.eventSource.x - this.context.eventSource.width/2) - this.touchBuffer
				local right = (this.context.eventSource.x + this.context.eventSource.width/2) + this.touchBuffer
				local top = (this.context.eventSource.y - this.context.eventSource.height/2) - this.touchBuffer
				local bottom = (this.context.eventSource.y + this.context.eventSource.height/2) + this.touchBuffer
				
				local startX, startY = this.context.eventSource.parent:contentToLocal(event.xStart, event.yStart)
				local currentX, currentY = this.context.eventSource.parent:contentToLocal(event.x, event.y)
				
				--com.splosive.trace("(" .. x .. "," .. y ..")  [" .. left .. " - " .. right.. " ] [  " .. top .. " | " .. bottom .. " ]", "View-Behavior-DragThrow")
				
				local eventSourceTouched = (startX >= left and startX <= right and startY >= top and startY <= bottom )
				if(event.phase == "began" and eventSourceTouched and this.context.event == "OBJECT_PRESS")then
			
					this.startX = left + (right - left)/2
					this.startY = top + (bottom - top)/2
					
					if(this.object)then
						this.object.x = this.startX
						this.object.y = this.startY
					end
					
					this.pressedEventSource = true
					if(this.object)then
						this.object.isVisible = true
					end
				elseif(event.phase == "began" and eventSourceTouched == false) then
					this.pressedEventSource = false
				elseif(event.phase == "ended") then
					if(this.pressedEventSource)then
						x = event.x
						y = event.y
						
						if(public.forceMode == public.FORCE_BY_DISTANCE)then
							this.calculateForceByDistance(this.startX, this.startY, x, y)
						elseif(public.forceMode == public.FIXED_BY_ANGLE)then
							x = event.x
							y = event.y
							
							local xOffset = this.startX
							local yOffset = this.startY
							--local angleBetween = this.mCeil(this.mAtan2( (currentY - yOffset), (currentX - xOffset) ) * 180 / this.mPi) + 90
							local angleBetween = this.calculateAngle(xOffset, yOffset, currentX, currentY)
							this.calculateFixedForceByAngle(angleBetween, this.fixedForceRadius)
						end
							
						public.execute()
					end
					
					if(this.object)then
						this.object.isVisible = false
					end
					
					if(this.distanceVector)then
						this.distanceVector:removeSelf()
						this.distanceVector = nil
					end
					
				else
					x = event.x
					y = event.y
					
					local xOffset = this.startX
					local yOffset = this.startY
					
					if(this.distanceVector)then
						this.distanceVector:removeSelf()
						this.distanceVector = nil
					end
					
					if(this.showDistanceVector == true)then
						this.distanceVector = display.newLine(this.context.target.parent, xOffset, yOffset, currentX, currentY)
						this.distanceVector:setColor( 255, 102, 102, 255 )
						this.distanceVector.width = 6
						 
						this.context.target:toFront()
					end
					
					if(this.object)then
						-- Formula: 90 + (math.atan2(y2 - y1, x2 - x1) * 180 / PI)
						--local angleBetween = this.mCeil(this.mAtan2( (currentY - yOffset), (currentX - xOffset) ) * 180 / this.mPi) + 90
						local angleBetween = this.calculateAngle(xOffset, yOffset, currentX, currentY)
						this.object.rotation = angleBetween --+ 180
						
						this.calculateFixedForceByAngle(angleBetween, this.fixedForceRadius)
						
					end
				end
				
				return true
			end
			
			protected.calculateAngle = function(xFrom, yFrom, xTo, yTo)
				local angleBetween = this.mCeil(this.mAtan2( (yTo - yFrom), (xTo - xFrom) ) * 180 / this.mPi) + 90
				
				if(angleBetween < this.minAngle)then 
					angleBetween = this.minAngle 
				elseif(angleBetween > this.maxAngle)then
					angleBetween = this.maxAngle
				end
				
				return angleBetween
			end
			
			protected.calculateForceByDistance = function(fromX, fromY, toX, toY)
				--this.xForce = ((x - this.startX)) * 15	--> 2.75
				--this.yForce = ((y - this.startY)) * 15	--> 2.75
				this.xForce = ((toX - fromX)) * 15	--> 2.75
				this.yForce = ((toY - fromY)) * 15	--> 2.75
				
				this.maxForce = this.context.descriptor.maxForce or 1500
			
				this.xForce = math.min(this.xForce, this.maxForce)
				this.yForce = math.min(this.yForce, this.maxForce)
				
			end
			
			protected.calculateFixedForceByAngle = function(angle, radius)
				angle = 90 - angle
				local adjacentCatet = radius * this.cos( this.rad( angle ) )
				local oppositeCatet = radius * this.sin( this.rad( angle ) )
				
				this.xForce = adjacentCatet * 15
				this.yForce = oppositeCatet * -15
				
				--com.splosive.trace("calculateFixedForceByAngle > angle = " .. angle .. ", this.xForce = " .. this.xForce .. ", this.yForce = " .. this.yForce, "View-Behavior-DragThrow")
				--com.splosive.trace("calculateFixedForceByAngle > this.cos( angle ) = " .. this.cos( angle ) .. ", this.sin( angle ) = " .. this.sin( angle ) , "View-Behavior-DragThrow")
				
			end
			
			
			public.execute = function()
				
				com.splosive.trace("calculateFixedForceByAngle > this.xForce = " .. this.xForce .. ", this.yForce = " .. this.yForce, "View-Behavior-DragThrow")
				
	
				this.context.target:applyForce( this.xForce, this.yForce, this.context.target.x, this.context.target.y )
				
				super.public.execute()
				
				this.executionNumber = this.executionNumber + 1
				if(this.executionLimit)then
					if(this.executionNumber >= this.executionLimit)then
						-- we don't call deactivate because that would deactivate the nested behaviors and we need those to stay active
						Runtime:removeEventListener( "touch", this.objectPressed )
					end
				end
				
			end
			
			return api
			
		end
		
		--[[
		================================================
		PointThrow 
		================================================
		]]
	
		local PointThrow = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.FORCE_BY_DISTANCE = "forceByDistance"
			public.FIXED_BY_ANGLE = "fixedByAngle"
			
			public.forceMode = FIXED_BY_ANGLE
			
			this.xForce = 0
			this.yForce = 0
			
			this.startX = 0
			this.startY = 0
			this.maxForce = 1500
			this.touchBuffer = 0
			this.pressedEventSource = false
			this.executionLimit = nil
			this.executionNumber = 0
			this.fixedForceRadius = nil
			
			protected.mCeil = math.ceil
			protected.mAtan2 = math.atan2
			protected.cos = math.cos
			protected.sin = math.sin
			protected.rad = math.rad
			protected.mPi = math.pi
			protected.mSqrt = math.sqrt
			protected.object = nil
			protected.parentContainer = nil
			
			protected.showDistanceVector = nil
			protected.distanceVector = nil
			
			protected.minAngle = nil
			protected.maxAngle = nil
			protected.objectColliding = false
			protected.jumpable = false
			
			public.activate = function()
				com.splosive.trace("PointThrow activate!", "View-Behavior-PointThrow")
				this.executionNumber = 0
				
				this.minAngle = this.context.descriptor.minAngle or -360
				this.maxAngle = this.context.descriptor.maxAngle or 360
				this.fixedForceRadius = this.context.descriptor.fixedForceRadius or 120
				public.forceMode = this.context.descriptor.forceMode or public.FIXED_BY_ANGLE
				this.xForce = this.context.descriptor.xForce or 0
				this.yForce = this.context.descriptor.yForce or 0
				this.touchBuffer = this.context.descriptor.touchBuffer or 0
				this.executionLimit = this.context.descriptor.executionLimit
				
				if(public.forceMode == public.FIXED_BY_ANGLE)then
					this.showDistanceVector = false
				end
				
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					Runtime:addEventListener( "touch", this.objectPressed )
				end
				
				-- we use target and not eventSource because eventSource is the background and target it the object we are gonna throw
				this.context.target:addEventListener("collision", this.objectCollision )
				
				super.public.activate()
			end
			
			public.deactivate = function()
			
				if(this.object ~= nil)then
					this.object:removeSelf()
					this.object = nil
				end
			
			 	Runtime:removeEventListener( "touch", this.objectPressed )
				this.context.target:removeEventListener("collision", this.objectCollision )
			 	super.public.deactivate()
			end
			
			protected.objectCollision = function(event)
				
				if(event.phase == "began") then
					this.objectColliding = true
					this.jumpable = true
					
					if(event.other.descriptor == nil)then
						this.jumpable = true
					else
						if(event.other.descriptor.isSensor == true)then
							this.jumpable = false
						end
						if(event.other.descriptor.isGround == true)then
							this.jumpable = false
						end
					end
				
			
				elseif(event.phase == "ended") then
					this.objectColliding = false
				end
			end
			
			protected.objectPressed = function(event)
			
				local left = (this.context.eventSource.x - this.context.eventSource.width/2) - this.touchBuffer
				local right = (this.context.eventSource.x + this.context.eventSource.width/2) + this.touchBuffer
				local top = (this.context.eventSource.y - this.context.eventSource.height/2) - this.touchBuffer
				local bottom = (this.context.eventSource.y + this.context.eventSource.height/2) + this.touchBuffer
				
				local startX, startY = this.context.eventSource.parent:contentToLocal(event.xStart, event.yStart)
				local currentX, currentY = this.context.eventSource.parent:contentToLocal(event.x, event.y)
				
				--com.splosive.trace("(" .. x .. "," .. y ..")  [" .. left .. " - " .. right.. " ] [  " .. top .. " | " .. bottom .. " ]", "View-Behavior-PointThrow")
				if( this.jumpable == true)then
					local eventSourceTouched = (startX >= left and startX <= right and startY >= top and startY <= bottom )
					if(eventSourceTouched and (event.phase == "began" and this.context.event == "OBJECT_PRESS") or (event.phase == "ended" and this.context.event == "OBJECT_RELEASE") )then
				
						local x = event.x
						local y = event.y
						local xOffset = this.context.target.x
						local yOffset = this.context.target.y
						
						if(public.forceMode == public.FORCE_BY_DISTANCE)then
							this.calculateForceByDistance(xOffset, yOffset, x, y)
						elseif(public.forceMode == public.FIXED_BY_ANGLE)then
							local angleBetween = this.calculateAngle(xOffset, yOffset, currentX, currentY)
							this.calculateFixedForceByAngle(angleBetween, this.fixedForceRadius)
						end
								
						public.execute()
						
					end
				end
				
				return true
			end
			
			protected.calculateAngle = function(xFrom, yFrom, xTo, yTo)
				local angleBetween = this.mCeil(this.mAtan2( (yTo - yFrom), (xTo - xFrom) ) * 180 / this.mPi) + 90
				
				if(angleBetween < this.minAngle)then 
					angleBetween = this.minAngle 
				elseif(angleBetween > this.maxAngle)then
					angleBetween = this.maxAngle
				end
				
				return angleBetween
			end
			
			protected.calculateForceByDistance = function(fromX, fromY, toX, toY)
				this.xForce = ((toX - fromX)) * 15	--> 2.75
				this.yForce = ((toY - fromY)) * 15	--> 2.75
				
				this.maxForce = this.context.descriptor.maxForce or 1500
			
				this.xForce = math.min(this.xForce, this.maxForce)
				this.yForce = math.min(this.yForce, this.maxForce)
				
			end
			
			protected.calculateFixedForceByAngle = function(angle, radius)
				angle = 90 - angle
				local adjacentCatet = radius * this.cos( this.rad( angle ) )
				local oppositeCatet = radius * this.sin( this.rad( angle ) )
				
				this.xForce = adjacentCatet * 15
				this.yForce = oppositeCatet * -15
				
			end
			
			
			public.execute = function()
				
				com.splosive.trace("calculateFixedForceByAngle > this.xForce = " .. this.xForce .. ", this.yForce = " .. this.yForce, "View-Behavior-PointThrow")
				this.context.target:applyForce( this.xForce, this.yForce, this.context.target.x, this.context.target.y )
				
				this.jumpable = false
				
				super.public.execute()
				
				this.executionNumber = this.executionNumber + 1
				if(this.executionLimit)then
					if(this.executionNumber >= this.executionLimit)then
						-- we don't call deactivate because that would deactivate the nested behaviors and we need those to stay active
						Runtime:removeEventListener( "touch", this.objectPressed )
					end
				end
				
			end
			
			return api
			
		end
		
		
		--[[
		================================================
		Vertical thrust 
		================================================
		]]
	
		local VerticalThrust = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.activate = function()
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					--this.context.eventSource.touch = this.objectPressed
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				--this.context.eventSource.touch = nil
				this.context.eventSource:removeEventListener( "touch", this.objectPressed)
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					public.execute()
					return true
				elseif(event.phase == "ended" and this.context.event == "OBJECT_RELEASE") then
					public.execute()
					return true
				end
			end
			
			public.execute = function()
				this.context.target:applyForce( 0, this.context.descriptor.force, this.context.target.x, this.context.target.y )
				super.public.execute()
			end
			
			return api
			
		end
		
		--[[
		================================================
		CollisionTrigger
		================================================
		]]
	
		local CollisionTrigger = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.activate = function()
				com.splosive.trace("CollisionTrigger > activate ", "View-Behavior-CollisionTrigger")
			
				if(this.context.eventSources ~= nil)then
					com.splosive.trace("CollisionTrigger > this.context.descriptor.eventSources = " .. this.context.descriptor.eventSources, "View-Behavior-CollisionTrigger")
					for k,v in pairs(this.context.eventSources) do
						com.splosive.trace("adding listenr to eventSource = " .. v.id, "View-Behavior-CollisionTrigger")
						--v.collision = this.objectCollision
						v:addEventListener( "collision", this.objectCollision )
					end
				else
					com.splosive.trace("CollisionTrigger > activate = this.context.eventSource = " .. this.context.descriptor.eventSource, "View-Behavior-CollisionTrigger")
					--this.context.eventSource.collision = this.objectCollision
					this.context.eventSource:addEventListener( "collision", this.objectCollision )
				end
				super.public.activate()
				
			end
			
			public.deactivate = function()
				if(this.context.eventSources ~= nil)then
					com.splosive.trace("CollisionTrigger > this.context.descriptor.eventSources = " .. this.context.descriptor.eventSources, "View-Behavior-CollisionTrigger")
					for k,v in pairs(this.context.eventSources) do
						com.splosive.trace("removing listener from eventSource = " .. v.id, "View-Behavior-CollisionTrigger")
						--v.collision = nil
						v:removeEventListener( "collision", this.objectCollision)
					end
				else
					com.splosive.trace("CollisionTrigger > deactivate = this.context.eventSource = " .. this.context.descriptor.eventSource, "View-Behavior-CollisionTrigger")
					--this.context.eventSource.collision = nil
					this.context.eventSource:removeEventListener( "collision", this.objectCollision)
				end
				super.public.deactivate()
				
			end
			
			protected.objectCollision = function(event)
				--com.splosive.trace("CollisionTrigger > objectCollision > ", "View-Behavior-CollisionTrigger")
				if(this.context.target ~= nil)then
					if(event.other == this.context.target) then
						--com.splosive.trace("collision!", "View-Behavior-CollisionTrigger")
						public.execute()
					end
				elseif(this.context.targets ~= nil)then
					for k,v in ipairs(this.context.targets) do
						if(event.other == v) then
							--com.splosive.trace("collision with " .. k, "View-Behavior-CollisionTrigger")
							public.execute()
						end				
					end
				end
			end
			
			public.execute = function()
				com.splosive.trace("CollisionTrigger > execute", "View-Behavior-CollisionTrigger")
				super.public.execute()
			end
			
			return api
			
		end
		
		
		package.Pause = Pause
		package.Resume = Resume
		package.ObjectSleepTrigger = ObjectSleepTrigger
		package.CollisionTrigger = CollisionTrigger
		package.SlingshotThrow = SlingshotThrow
		package.DragThrow = DragThrow
		package.PointThrow = PointThrow
		package.VerticalThrust = VerticalThrust
		
		
		return package
	
	
	end
	
	
	
--[[
	================================================
	Camera package: Contains behaviors associated with the camera
	================================================
	]]
	
	local camera = function()
		
		local package = {}
	
		--[[
		================================================
		DragView
		================================================
		]]
	
		local DragView = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			this.previousInstant = system.getTimer()
			this.parentContainer = nil
			
			this.lastX = nil
			this.lastY = nil
			protected.startX = 0
			protected.startY = 0
			this.currentX = nil
			this.currentY = nil
			this.pressed = false
			this.inFocus = false
			
			public.activate = function()
				com.splosive.trace("DragView > activate > ", "View-Behavior-DragView")
				this.camera  = this.context.currentView.getCamera()--com.splosive.camera
				
				if(this.context.descriptor.thresholdCondition == nil)then
					this.context.descriptor.thresholdCondition = "AND"
				end
				
				if(this.context.descriptor.thresholdX ~= nil)then
					if(this.context.descriptor.thresholdMode == nil)then
						this.context.descriptor.thresholdMode = "absolute"
					end
					if(this.context.descriptor.thresholdY == nil)then
						this.context.descriptor.thresholdY = 0
					end
				end
				if(this.context.descriptor.thresholdY ~= nil)then
					if(this.context.descriptor.thresholdMode == nil)then
						this.context.descriptor.thresholdMode = "absolute"
					end
					if(this.context.descriptor.thresholdX == nil)then
						this.context.descriptor.thresholdX = 0
					end
				end
				
				
				this.parentContainer = this.camera.getParent()
				
				-- *Because this is a camera behavior,we don't need to store the touch property and we can go with the easier approach
				--   Also for some reason it wasn't always working with the other syntax
				--this.parentContainer.touch = this.touchEvent
				this.parentContainer:addEventListener( "touch", this.touchEvent )
				super.public.activate()
			end
			
			public.deactivate = function()
				--this.parentContainer.touch = nil
				this.parentContainer:removeEventListener( "touch", this.touchEvent )
				super.public.deactivate()
			end
			
			protected.touchEvent = function(event)
				com.splosive.trace("DragView > touch phase  = " .. event.phase .. ", event.x = " .. event.x .. ", event.y = " .. event.y, "View-Behavior-DragView")
			
				if(event.phase == "moved" and this.pressed)then
					--com.splosive.trace("DragView > touch phase  = " .. event.phase .. ", event.x = " .. event.x .. ", event.y = " .. event.y, "View-Behavior-DragView")
					this.currentX = event.x
					this.currentY = event.y
					
					if(this.lastX ~= nil and this.lastY ~= nil)then
						public.execute()
					end
					
					this.lastX = this.currentX
					this.lastY = this.currentY
					
					local crossedThreshold = true
					if(this.context.descriptor.thresholdMode ~= nil)then
						if(this.context.descriptor.thresholdMode == "directional")then
							if(this.context.descriptor.thresholdX > 0)then
								crossedThreshold = crossedThreshold and ( (event.x - this.startX) >= this.context.descriptor.thresholdX)
							elseif(this.context.descriptor.thresholdX < 0)then
								crossedThreshold = crossedThreshold and ( (event.x - this.startX) <= this.context.descriptor.thresholdX)
							end
							
							if(this.context.descriptor.thresholdY > 0)then
								crossedThreshold = crossedThreshold and ( (event.y - this.startY) >= this.context.descriptor.thresholdY)
							elseif(this.context.descriptor.thresholdY < 0)then
								crossedThreshold = crossedThreshold and ( (event.y - this.startY) <= this.context.descriptor.thresholdY)
							end
						elseif(this.context.descriptor.thresholdMode == "absolute")then
							if(this.context.descriptor.thresholdCondition == "OR")then
								crossedThreshold = crossedThreshold and ( ( math.abs(event.y - this.startY) >= math.abs(this.context.descriptor.thresholdY)) or ( math.abs(event.x - this.startX) >= math.abs(this.context.descriptor.thresholdX)) )
							elseif(this.context.descriptor.thresholdCondition == "AND") then
								crossedThreshold = crossedThreshold and ( ( math.abs(event.y - this.startY) >= math.abs(this.context.descriptor.thresholdY)) and ( math.abs(event.x - this.startX) >= math.abs(this.context.descriptor.thresholdX)) )
							end
							
						end
					
						if(crossedThreshold == true)then
							display.getCurrentStage():setFocus( this.parentContainer )
							this.inFocus = true
						end
					end
					
				else
					this.lastX = nil
					this.lastY = nil
				
				end
				
				if(event.phase == "began")then
				
					if(this.pressed == nil or this.pressed == false)then
						this.pressed = true
						this.startX = event.x
						this.startY = event.y
						
						if(this.context.descriptor.thresholdMode == nil)then
							display.getCurrentStage():setFocus( this.parentContainer )
							this.inFocus = true
						end
					else
						this.pressed = false
						display.getCurrentStage():setFocus( nil )
					end
					
				elseif(event.phase == "ended")then
					if(this.pressed == true)then
						this.pressed = false
						display.getCurrentStage():setFocus( nil )
						if(this.inFocus)then
							event.handled = true
							this.inFocus = false
						end
					end
				end
				
				return true
			end
			
			public.execute = function()
				
				local panX
				local panY
				local deltaX
				local deltaY
				
				if(this.context.descriptor.axis == nil or this.context.descriptor.axis == "x") then
					deltaX = (this.currentX - this.lastX)
					panX = this.camera.getX() - deltaX
				end
				
				if(this.context.descriptor.axis == nil or this.context.descriptor.axis == "y") then
					deltaY =  (this.currentY - this.lastY)
					panY =  this.camera.getY() - deltaY
				end
				
				if(deltaX)then
					--com.splosive.trace("DragView > execute >  deltaX = " .. deltaX .. ", this.camera.getX() = " .. this.camera.getX(), "View-Behavior-DragView")
				end
				if(deltaY)then
					--com.splosive.trace("DragView > execute >  deltaY = " .. deltaY .. ", this.camera.getY() = " .. this.camera.getY(), "View-Behavior-DragView")
				end
				
				this.camera.panBy(deltaX, deltaY)
				--this.camera.panTo(panX, panY)
				super.public.execute()
				
			end
			
			return api
			
		end
		
		--[[
		================================================
		PinchZoomView
		================================================
		]]
	
		local PinchZoomView = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			this.previousInstant = system.getTimer()
			this.parentContainer = nil
			
			this.lastX = nil
			this.lastY = nil
			protected.startX = 0
			protected.startY = 0
			this.currentX = nil
			this.currentY = nil
			this.pressed = false
			
			public.activate = function()
			 	com.splosive.trace( "PinchZoomView > activate  >", "View-Behavior-PinchZoomView" )
			 	
				this.camera  = this.context.currentView.getCamera()--com.splosive.camera
				
			 	local isSimulator = "simulator" == system.getInfo("environment")
			 	if(isSimulator)then
				 	com.splosive.trace( "PinchZoomView > Multitouch not supported on Simulator!", "View-Behavior-PinchZoomView" )
			 	else
					system.activate( "multitouch" )
			 	end
				
				if(this.context.descriptor.thresholdMode == nil)then
					this.context.descriptor.thresholdMode = "absolute"
				end
				if(this.context.descriptor.thresholdX == nil)then
					this.context.descriptor.thresholdX = 0
				end
				if(this.context.descriptor.thresholdY == nil)then
					this.context.descriptor.thresholdY = 0
				end
				
				this.parentContainer = this.camera.getParent()
				this.parentContainer.touch = this.touchEvent
				this.parentContainer:addEventListener( "touch", this.parentContainer )
				super.public.activate()
			end
			
			public.deactivate = function()
				this.parentContainer.touch = nil
				this.parentContainer:removeEventListener( "touch", this.parentContainer )
				super.public.deactivate()
			end
			
			protected.calculateDelta = function( previousTouches, event )
		        local id,touch = next( previousTouches )
		        if event.id == id then
		                id,touch = next( previousTouches, id )
		                assert( id ~= event.id )
		        end
		 
		        local dx = touch.x - event.x
		        local dy = touch.y - event.y
		        return dx, dy
			end
			
			
			protected.calculateTouchCenter = function(self, previousTouches, event)
		        local id,touch = next( previousTouches )
		        if event.id == id then
		                id,touch = next( previousTouches, id )
		                assert( id ~= event.id )
		        end
		 		
		 		local x2, y2 = self:contentToLocal(touch.x, touch.y)
		 		local x1, y1 = self:contentToLocal(event.x, event.y)
		 		
		        local cx = x1 + (x2 - x1)/2
		        local cy = y1 + (y2 - y1)/2
		        
		        return {x=cx, y=cy}
				
			end
			
			protected.touchEvent = function(self, event)
				--com.splosive.trace( "PinchZoomView > touchEvent > " .. event.phase, "View-Behavior-PinchZoomView" )
				local result = true
	 
		        local phase = event.phase
		 
		        local previousTouches = self.previousTouches
		 
		        local numTotalTouches = 1
		        if ( previousTouches ) then
		                -- add in total from previousTouches, subtract one if event is already in the array
		                numTotalTouches = numTotalTouches + self.numPreviousTouches
		                if previousTouches[event.id] then
		                        numTotalTouches = numTotalTouches - 1
		                end
		        end
		 
		        if "began" == phase then
		                -- Very first "began" event
		                if ( not self.isFocus ) then
		                        -- Subsequent touch events will target button even if they are outside the stageBounds of button
		                        display.getCurrentStage():setFocus( self )
		                        self.isFocus = true
		 
		                        previousTouches = {}
		                        self.previousTouches = previousTouches
		                        self.numPreviousTouches = 0
		                elseif ( not self.distance ) then
		                        
		                        local dx,dy
		 
		                        if previousTouches and ( numTotalTouches ) >= 2 then
		                                dx,dy = this.calculateDelta( previousTouches, event )
		                        end
		 
		                        -- initialize to distance between two touches
		                        if ( dx and dy ) then
		                                local d = math.sqrt( dx*dx + dy*dy )
		                                if ( d > 0 ) then
		                                        self.distance = d
		                                        if(self.originalScaleRecorded == nil) then 
			                                        self.xScaleOriginal = self.xScale
			                                        self.yScaleOriginal = self.yScale 
			                                        self.originalScaleRecorded = true
		                                        end
		                                        self.xScaleBase = self.xScale
		                                        self.yScaleBase = self.yScale 
		                                        --self.touchCenter = this.calculateTouchCenter(self, previousTouches, event)
		                                        --self.touchCenter.scale = self.xScaleBase
		                                        
		                                        --self.xReferenceOriginal = self.xReference
                                        		--self.yReferenceOriginal = self.yReference
		                                        
		                                        --com.splosive.trace( "self BEF INIT :  x = " .. self.x .. ", y = " .. self.y , "View-Behavior-PinchZoomView" )
		                                        
		                                        --self.xReference = self.touchCenter.x
				                                --self.yReference = self.touchCenter.y
		                                        
		                                        --com.splosive.trace( "self AFT INIT :  x = " .. self.x .. ", y = " .. self.y , "View-Behavior-PinchZoomView" )
		                                        --com.splosive.trace( "touchCenter INIT :  x = " .. self.touchCenter.x .. ", y = " .. self.touchCenter.y ..", scale = " .. self.touchCenter.scale, "View-Behavior-PinchZoomView" )
		                                        --com.splosive.trace( "Reference INIT :  x = " .. self.xReferenceOriginal .. ", y = " .. self.yReferenceOriginal , "View-Behavior-PinchZoomView" )
		                                        --com.splosive.trace( "distance = " .. self.distance, "View-Behavior-PinchZoomView" )
		                                end
		                        end
		                end
		 
		                if not previousTouches[event.id] then
		                        self.numPreviousTouches = self.numPreviousTouches + 1
		                end
		                previousTouches[event.id] = event
		 
		        elseif self.isFocus then
		                if "moved" == phase then
		                        if ( self.distance ) then
		                                local dx,dy
		                                if previousTouches and ( numTotalTouches ) >= 2 then
		                                        dx,dy = this.calculateDelta( previousTouches, event )
		                                end
		        
		                                if ( dx and dy ) then
		                                        local newDistance = math.sqrt( dx*dx + dy*dy )
		                                        local scale = newDistance / self.distance
		                                        --com.splosive.trace( "newDistance(" ..newDistance .. ") / distance(" .. self.distance .. ") = scale("..  scale ..")" , "View-Behavior-PinchZoomView" )
		                                        local newScaleX = self.xScaleBase * scale
		                                        local newScaleY = self.yScaleBase * scale
		                                        if ( scale > 0 and newScaleX > self.xScaleOriginal and newScaleY > self.yScaleOriginal) then
		                                        
		                                                self.xScale = newScaleX
		                                                self.yScale = newScaleY
		                                                
														-- this pan is just to cause the validation of the camera to run, to make sure we are restricting the movements
		                                                this.camera.panBy(.01, .01)
				                                        
		                                                --[[
		                                                if(self.touchCenter ~= nil)then
					                                        com.splosive.trace( "move touchCenter >  x = " .. self.touchCenter.x .. ", y = " .. self.touchCenter.y .. ", scale = ".. self.touchCenter.scale , "Camera" )
			                                                
			                                                -- position the container  so that it seems to scale around the center of our touch
			                                                local deltaX = (self.touchCenter.x * newScaleX) - ( self.touchCenter.x * self.touchCenter.scale )
			                                                local deltaY = (self.touchCenter.y * newScaleY) - ( self.touchCenter.y * self.touchCenter.scale )
			                                                
					                                        com.splosive.trace( "panBy(" ..-deltaX .. ", " .. -deltaY .. ")" , "Camera" )
			                                                this.camera.panBy(-deltaX, -deltaY)
			                                                
			                                                self.touchCenter.scale = newScaleX
		                                                end
		                                                ]]
		                                                
		                                        end
		                                end
		                        end
		 
		                        if not previousTouches[event.id] then
		                                self.numPreviousTouches = self.numPreviousTouches + 1
		                        end
		                        previousTouches[event.id] = event
		 
		                elseif "ended" == phase or "cancelled" == phase then
		                        if previousTouches[event.id] then
		                                self.numPreviousTouches = self.numPreviousTouches - 1
		                                previousTouches[event.id] = nil
		                        end
		 
		                        if ( #previousTouches > 0 ) then
		                                -- must be at least 2 touches remaining to pinch/zoom
		                                self.distance = nil
		                        else
		                        		
		                        		--[[
		                        		if(self.touchCenter ~= nil)then
	                                        com.splosive.trace( "self BEF END :  x = " .. self.x .. ", y = " .. self.y , "View-Behavior-PinchZoomView" )
	                        				self.xReference = 0--(self.touchCenter.x )
	                                        self.yReference = 0--(self.touchCenter.y )
	                                        
	                                        com.splosive.trace( "self AFT END :  x = " .. self.x .. ", y = " .. self.y , "View-Behavior-PinchZoomView" )
	                                        com.splosive.trace( "Reference END :  x = " .. self.xReference .. ", y = " .. self.yReference , "View-Behavior-PinchZoomView" )
			                        		self.touchCenter = nil
                                        end
                                        ]]
		                        		
		                                -- previousTouches is empty so no more fingers are touching the screen
		                                -- Allow touch events to be sent normally to the objects they "hit"
		                                display.getCurrentStage():setFocus( nil )
		                                
		 
		                                self.isFocus = false
		                                self.distance = nil
		                                self.xScaleBase = nil
		                                self.yScaleBase = nil
		 
		                                -- reset array
		                                self.previousTouches = nil
		                                self.numPreviousTouches = nil
		                        end
		                end
		        end
		 
		        return result
			end
			
			public.execute = function()
				super.public.execute()
			end
			
			return api
			
		end
		
		
		--[[
		================================================
		Follow object
		================================================
		]]
	
		local FollowObject = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			this.previousInstant = system.getTimer()
			
			public.activate = function()
				this.camera  =  this.context.currentView.getCamera() --com.splosive.camera
				
				if(this.context.descriptor.xOffset == nil)then this.context.descriptor.xOffset = 0 end
				if(this.context.descriptor.yOffset == nil)then this.context.descriptor.yOffset = 0 end
				
				this.previousInstant = system.getTimer()
				Runtime:addEventListener( "enterFrame", this.onEnterFrame )
				
				super.public.activate()
			end
			
			public.deactivate = function()
				Runtime:removeEventListener( "enterFrame", this.onEnterFrame )
				super.public.deactivate()
			end
			
			protected.onEnterFrame = function( event )
				local tDelta = event.time - this.previousInstant
				this.previousInstant = event.time
				
				public.execute()
				 
			end
			
			
			public.execute = function()
				
				local panX
				local panY
				
				if(this.context.descriptor.axis == nil or this.context.descriptor.axis == "x") then
					panX = this.context.target.x - this.context.descriptor.xOffset
				end
				if(this.context.descriptor.axis == nil or this.context.descriptor.axis == "y") then
					panY = this.context.target.y - this.context.descriptor.yOffset
				end	
				
				this.camera.panTo(panX, panY)
				
				super.public.execute()
			end
			
			return api
			
		end
		
		--[[
		================================================
		KeepInView
		================================================
		]]
		
		local KeepInView = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			protected.directionX = 0
			protected.directionY = 0
			protected.lastObjectX = 0
			protected.lastObjectY = 0
			
			public.activate = function()
				this.camera  =  this.context.currentView.getCamera() --com.splosive.camera
				
				if(this.context.descriptor.xOffset == nil)then this.context.descriptor.xOffset = 0 end
				if(this.context.descriptor.yOffset == nil)then this.context.descriptor.yOffset = 0 end
				
				
				this.lastObjectX = this.context.target.x
				this.lastObjectY = this.context.target.y
					
				Runtime:addEventListener( "enterFrame", this.onEnterFrame )
				
				super.public.activate()
			end
			
			public.deactivate = function()
				Runtime:removeEventListener( "enterFrame", this.onEnterFrame )
				super.public.deactivate()
			end
			
			protected.onEnterFrame = function( event )
				if(this.lastObjectX ~= this.context.target.x or this.lastObjectY ~= this.context.target.y)then
				
					this.directionX = math.floor(this.context.target.x - this.lastObjectX)
					this.directionY = math.floor(this.context.target.y - this.lastObjectY)
				
					--com.splosive.trace("this.directionX = " .. this.directionX .. ", this.directionY = " .. this.directionY, "View-Behavior-KeepInView")
					public.execute()
					
					this.lastObjectX = this.context.target.x
					this.lastObjectY = this.context.target.y
				end
				 
			end
			
			
			public.execute = function()
				
				
				local camX = this.camera.getX()
				local camY = this.camera.getY()
				
				--com.splosive.trace("KeepInView > camX = ".. camX .. " vs " .. this.context.target.x, "View-Behavior-KeepInView")
				local panX = nil
				local panY = nil
				
				if(this.context.descriptor.axis == nil or this.context.descriptor.axis == "x") then
					local edgeDistanceX = (display.contentWidth/2 - this.context.descriptor.xOffset)
					
					if(this.context.target.x - camX >  edgeDistanceX and this.directionX > 1 )then
						panX = camX + (this.context.target.x - camX) - edgeDistanceX
					elseif(camX - this.context.target.x > edgeDistanceX   and this.directionX < -1)then
						panX = camX - ((camX - this.context.target.x) - edgeDistanceX)
					end
					
				end
				
				if(this.context.descriptor.axis == nil or this.context.descriptor.axis == "y") then
					local edgeDistanceY = (display.contentHeight/2 - this.context.descriptor.yOffset)
					if(this.context.target.y - camY >  edgeDistanceY and this.directionY > 1)then
						panY = camY + (this.context.target.y - camY) - edgeDistanceY
					elseif(camY - this.context.target.y > edgeDistanceY and this.directionY < -1)then
						panY = -camY - ((camY - this.context.target.y) - edgeDistanceY)
					end
				end
			
				this.camera.panTo(panX, panY)
				
				
				super.public.execute()
			end
			
			return api
			
		end
		
		
	
		package.DragView = DragView
		package.PinchZoomView = PinchZoomView
		package.FollowObject = FollowObject
		package.KeepInView = KeepInView
		
		
		return package
	
	
	end
		
--[[
	================================================
	interactive package: Contains interactive behaviors
	================================================
	]]
	
	local interactive = function()
		
		local package = {}
		
		--[[
		================================================
		TouchTrigger
		================================================
		]]
	
		local TouchTrigger = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			protected.focusedItem = nil
			
			public.activate = function()
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				if(this.context.eventSource ~= nil)then
					this.context.eventSource:removeEventListener( "touch", this.objectPressed )
				end
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					public.execute()
					if(this.context.descriptor.setFocus == true)then
						this.focusedItem = this.context.eventSource
						display.getCurrentStage():setFocus( this.focusedItem )
					end
				elseif(event.phase == "ended" and this.context.event == "OBJECT_RELEASE") then
					public.execute()
				end
				
				if(event.phase == "ended")then
					if(this.focusedItem ~= nil)then
						display.getCurrentStage():setFocus( nil )
						this.focusedItem = nil
					end
				end
				
				return true
			end
			
			public.execute = function()
				super.public.execute()
			end
			
			
			return api
			
		end
		
		
	
		--[[
		================================================
		DragItem
		================================================
		]]
	
		local DragItem = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.draggedItem = nil
			public.copiedObject = false
			protected.startX = 0
			protected.startY = 0
			protected.dropAccepted = false
			
			public.activate = function()
				com.splosive.trace("DragItem > activate", "View-Behavior-DragItem")
	
				if(this.context.descriptor.thresholdX ~= nil)then
					if(this.context.descriptor.thresholdMode == nil)then
						this.context.descriptor.thresholdMode = "absolute"
					end
					if(this.context.descriptor.thresholdY == nil)then
						this.context.descriptor.thresholdY = 0
					end
				end
				if(this.context.descriptor.thresholdY ~= nil)then
					if(this.context.descriptor.thresholdMode == nil)then
						this.context.descriptor.thresholdMode = "absolute"
					end
					if(this.context.descriptor.thresholdX == nil)then
						this.context.descriptor.thresholdX = 0
					end
				end
			
				if(this.context.eventSources ~= nil)then
					com.splosive.trace("DragItem > this.context.descriptor.eventSources = " .. this.context.descriptor.eventSources, "View-Behavior-DragItem")
					for k,v in pairs(this.context.eventSources) do
						com.splosive.trace("adding listenr to eventSource = " .. v.id, "View-Behavior-PointsToken")
						v.touch = this.objectTouch
						v:addEventListener( "touch", v )
					end
				elseif(this.context.eventSource ~= nil)then
					com.splosive.trace("DragItem > activate = this.context.eventSource = " .. this.context.descriptor.eventSource, "View-Behavior-DragItem")
					this.context.eventSource.touch = this.objectTouch
					this.context.eventSource:addEventListener( "touch",  this.context.eventSource)
				else
					com.splosive.trace("DragItem > activate > no event source :(", "View-Behavior-DragItem")
					
				end
				
				super.public.activate()
			end
			
			public.deactivate = function()
			
				if(this.context.eventSources ~= nil)then
					com.splosive.trace("DragItem > this.context.descriptor.eventSources = " .. this.context.descriptor.eventSources, "View-Behavior-DragItem")
					for k,v in pairs(this.context.eventSources) do
						if(v ~= nil)then
							com.splosive.trace("removing listener from eventSource = " .. v.id, "View-Behavior-DragItem")
							v.touch = nil
							v:removeEventListener( "touch", v )
						end
					end
				elseif(this.context.eventSource ~= nil)then
					com.splosive.trace("DragItem > deactivate = this.context.eventSource = " .. this.context.descriptor.eventSource, "View-Behavior-DragItem")
					this.context.eventSource.touch = nil
					this.context.eventSource:removeEventListener( "touch", this.context.eventSource )
				end
				
				super.public.deactivate()
			end
			
			protected.objectTouch = function(self, event)
				local handled = false
				local x, y = self.parent:contentToLocal(event.x, event.y)
				--com.splosive.trace("DragItem > touch phase  = " .. event.phase, "View-Behavior-DragItem")
				if(event.phase == "began") then
					this.startX = x
					this.startY = y
					
					if(this.context.descriptor.thresholdMode == nil and public.draggedItem == nil)then
						this.startDragging(self)
						handled = true
					end
				elseif(event.phase == "moved")then
				
					if(this.context.descriptor.thresholdMode ~= nil)then
						local crossedThreshold = true
						if(this.context.descriptor.thresholdMode == "directional")then
							if(this.context.descriptor.thresholdX > 0)then
								crossedThreshold = crossedThreshold and ( (event.x - this.startX) >= this.context.descriptor.thresholdX)
							elseif(this.context.descriptor.thresholdX < 0)then
								crossedThreshold = crossedThreshold and ( (event.x - this.startX) <= this.context.descriptor.thresholdX)
							end
							
							if(this.context.descriptor.thresholdY > 0)then
								crossedThreshold = crossedThreshold and ( (event.y - this.startY) >= this.context.descriptor.thresholdY)
							elseif(this.context.descriptor.thresholdY < 0)then
								crossedThreshold = crossedThreshold and ( (event.y - this.startY) <= this.context.descriptor.thresholdY)
							end
						elseif(this.context.descriptor.thresholdMode == "absolute")then
							crossedThreshold = crossedThreshold and ( math.abs(event.y - this.startY) >= math.abs(this.context.descriptor.thresholdY))
							crossedThreshold = crossedThreshold and ( math.abs(event.x - this.startX) >= math.abs(this.context.descriptor.thresholdX))
						end
					
						if(public.draggedItem == nil and crossedThreshold == true)then
							this.startDragging(self)
						end
					end
					
					if(public.draggedItem ~= nil)then
						com.splosive.trace("DragItem > move event.x = " .. x .. ", event.y = " .. y, "Editor")
						public.draggedItem.x = x
						public.draggedItem.y = y
						
						public.draggedItem.descriptor.x = x - public.draggedItem.width/2
						public.draggedItem.descriptor.y = y - public.draggedItem.height/2
						
						handled = true
					end
				elseif(event.phase == "ended" or event.phase == "cancelled") then
					display.getCurrentStage():setFocus( nil )
					if(public.draggedItem)then
					
						if( this.context.descriptor.onDragEnd ~= nil)then
							this.context.descriptor.onDragEnd( public.draggedItem )
						end
					
						public.execute()
						handled = true
					end
					
					timer.performWithDelay( 50, this.cleanDraggedItem )
				end
				
				
				return handled
			end
			
			
			protected.startDragging = function(item)
				local duplicateType = this.context.descriptor.duplicate
			
				if(duplicateType == "payload")then
					-- if there is a playload use it
					if(item.descriptor.payload ~= nil)then
						public.draggedItem = this.context.currentView.createObjectFromDescriptor(item.descriptor.payload, nil, true)
						if(public.draggedItem)then
							--display:insert(public.draggedItem)
							public.draggedItem.touch = this.objectTouch
							public.draggedItem:addEventListener( "touch",  public.draggedItem)
							public.copiedObject = true
						end
					-- otherwise, revert the duplicate to straight copying
					else
						duplicateType = true
					end
				end
				
				-- if duplicate is true, make a copy of the item via de view
				if(duplicateType == true)then
					public.draggedItem = this.context.currentView.duplicateObject(item)
					if(public.draggedItem)then
						--display:insert(public.draggedItem)
						public.draggedItem.touch = this.objectTouch
						public.draggedItem:addEventListener( "touch",  public.draggedItem)
						public.copiedObject = true
					end
				
				-- if duplicate is not set we are dragging this actual object
				elseif(duplicateType == false or duplicateType == nil)then
					public.copiedObject = false
					public.draggedItem = item
				end
				
				display.getCurrentStage():setFocus( public.draggedItem )
				
				if( this.context.descriptor.onStartDrag ~= nil)then
					this.context.descriptor.onStartDrag( public.draggedItem )
				end
			end
			
			
			protected.cleanDraggedItem = function(event)
				if(public.copiedObject == true and public.draggedItem)then
					public.draggedItem.touch = nil
					public.draggedItem:removeEventListener( "touch",  public.draggedItem)
					
					if(this.dropAccepted == false)then
						public.draggedItem:removeSelf()
					end
					
					public.copiedObject = false
				end
				
				public.draggedItem = nil
				com.splosive.trace("DragItem > after cleaning draggedItems ", "View-Behavior-DragItem")
			end
			
			protected.onExecute = function()
				if(this.context.descriptor.onExecute ~= nil)then
					this.dropAccepted = this.context.descriptor.onExecute(public.draggedItem)
				end
			end
			
			public.execute = function()
				super.public.execute()
			end
			
			
			return api
			
		end
		
		
	
		package.DragItem = DragItem
		package.TouchTrigger = TouchTrigger
		
		
		return package
	
	
	end
	
	
--[[
	================================================
	Sprite package: Contains behaviors associated with sprites
	================================================
	]]
	
	local sprite = function()
		
		local package = {}
	
		--[[
		================================================
		Play
		================================================
		]]
	
		local Play = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.activate = function()
				if(this.context.eventSource ~= nil)then
					--this.context.eventSource.collision = this.objectCollision
					this.context.eventSource:addEventListener( "collision", this.objectCollision)
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				if(this.context.eventSource ~= nil)then
					--this.context.eventSource.collision = nil
					this.context.eventSource:removeEventListener( "collision", this.objectCollision )
				end
				super.public.deactivate()
			end
			
			protected.objectCollision = function(event)
				if(event.phase == "began" and this.context.event == "COLLISION_BEGIN") then
					public.execute()
				elseif(event.phase == "ended" and this.context.event == "COLLISION_END") then
					public.execute()
				end
			end
			
			public.execute = function()
				this.context.target:prepare(this.context.descriptor.sequence)
				this.context.target:play()
				super.public.execute()
			end
			
			
			return api
			
		end
		
		
	
		package.Play = Play
		
		
		return package
	
	
	end
	
	
	
--[[
	================================================
	View package: Contains behaviors associated with viewmanager
	================================================
	]]
	
	local view = function()
		
		local package = {}
	
		--[[
		================================================
		ChangeView
		================================================
		]]
	
		local ChangeView = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			this.ViewManager = com.splosive.ViewManager
			
			public.activate = function()
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					--this.context.eventSource.touch = this.objectPressed
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				if(this.context.eventSource ~= nil)then
					--this.context.eventSource.touch = nil
					this.context.eventSource:removeEventListener( "touch", this.objectPressed )
				end
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					public.execute()
					return true
				elseif(event.phase == "ended" and this.context.event == "OBJECT_RELEASE") then
					public.execute()
					return true
				end
				
			end
			
			public.execute = function()
				this.ViewManager.changeView( this.context.descriptor.view , this.context.descriptor.params)
				super.public.execute()
			end
			
			
			return api
			
		end
		
		--[[
		================================================
		ResetView
		================================================
		]]
	
		local ResetView = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			this.ViewManager = com.splosive.ViewManager
			
			public.activate = function()
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					--this.context.eventSource.touch = this.objectPressed
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				if(this.context.eventSource ~= nil)then
					--this.context.eventSource.touch = nil
					this.context.eventSource:removeEventListener( "touch", this.objectPressed )
				end
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					public.execute()
				elseif(event.phase == "ended" and this.context.event == "OBJECT_RELEASE") then
					public.execute()
				end
				
				return true
			end
			
			public.execute = function()
				this.ViewManager.resetView( )
				super.public.execute()
			end
			
			
			return api
			
		end
		
		--[[
		================================================
		ChangeToPreviousView
		================================================
		]]
	
		local ChangeToPreviousView = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			this.ViewManager = com.splosive.ViewManager
			
			public.activate = function()
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					--this.context.eventSource.touch = this.objectPressed
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				if(this.context.eventSource ~= nil)then
					--this.context.eventSource.touch = nil
					this.context.eventSource:removeEventListener( "touch", this.objectPressed )
				end
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					public.execute()
				elseif(event.phase == "ended" and this.context.event == "OBJECT_RELEASE") then
					public.execute()
				end
				
				return true
			end
			
			public.execute = function()
				this.ViewManager.changeToPreviousView( )
				super.public.execute()
			end
			
			
			return api
			
		end
	
		package.ChangeView = ChangeView
		package.ChangeToPreviousView = ChangeToPreviousView
		package.ResetView = ResetView
		
		
		return package
	
	
	end
	
--[[
	================================================
	property package: Contains behaviors related to watching properties over time
	================================================
	]]
	
	local property = function()
		
		local package = {}
	
		--[[
		================================================
		watchGT executes an action when a property is Greater Than a targetValue
		================================================
		]]
	
		local watchGT = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			
			public.activate = function()
				com.splosive.trace("watchGT > activate", "View-Behavior-watchGT")
				Runtime:addEventListener( "enterFrame", this.onEnterFrame )
				super.public.activate()
			end
			
			public.deactivate = function()
				com.splosive.trace("watchGT > deactivate", "View-Behavior-watchGT")
				Runtime:removeEventListener( "enterFrame", this.onEnterFrame )
				super.public.deactivate()
			end
			
			protected.onEnterFrame = function(event)
				if(this.context.target[this.context.descriptor.property] > this.context.descriptor.targetValue)then
					public.execute()
					Runtime:removeEventListener( "enterFrame", this.onEnterFrame )
				end
			end
			
			public.execute = function()
				com.splosive.trace("watchGT > execute", "View-Behavior-watchGT")
				super.public.execute()
			end
			
			
			return api
			
		end
		
		--[[
		================================================
		Toggle is a simple action that sets a property to the opposite of its boolean state, it can be nested in another behavior to set a property when a specific trigger occurs
		================================================
		]]
	
		local Toggle = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			
			public.activate = function()
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					--this.context.eventSource.touch = this.objectPressed
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				if(this.context.eventSource ~= nil)then
					--this.context.eventSource.touch = nil
					this.context.eventSource:removeEventListener( "touch", this.objectPressed )
				end
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				com.splosive.trace("Toggle > objectPressed > phase = " .. event.phase, "View-Behaviors-DragItem")
				if(event.handled ~= nil)then
					com.splosive.trace("Toggle > objectPressed > event has been handle do nothing ", "View-Behaviors-DragItem")
					return true
				end
			
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					public.execute()
					return true
				elseif(event.phase == "ended" and this.context.event == "OBJECT_RELEASE") then
					public.execute()
					return true
				end
			end
			
			public.execute = function()
				com.splosive.trace("Toggle > execute > ", "View-Behaviors-DragItem")
			
				if(this.context.target ~= nil)then
					if(this.context.target[this.context.descriptor.property] == true)then
						this.context.target[this.context.descriptor.property] = false
					else
						this.context.target[this.context.descriptor.property] = true
					end
				elseif(this.context.targets ~= nil)then
					for k,v in ipairs(this.context.targets) do
						if(v[this.context.descriptor.property] == true)then
							v[this.context.descriptor.property] = false
						else
							v[this.context.descriptor.property] = true
						end
					end				
				end
				
				super.public.execute()
			end
			
			
			return api
			
		end
		--[[
		================================================
		Set is a simple action that sets a property, it can be nested in another behavior to set a property when a specific trigger occurs
		================================================
		]]
	
		local Set = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.activate = function()
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					com.splosive.trace("Set > activate >" , "View-property-Set")
					--this.context.eventSource.touch = this.objectPressed
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				com.splosive.trace("Set > deactivate >" , "View-property-Set")
				if(this.context.eventSource ~= nil)then
					com.splosive.trace("this.context.eventSource = " .. this.context.eventSource.id, "View-property-Set")
					--this.context.eventSource.touch = nil
					this.context.eventSource:removeEventListener( "touch", this.objectPressed )
				end
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					public.execute()
					return true
				elseif(event.phase == "ended" and this.context.event == "OBJECT_RELEASE") then
					public.execute()
					return true
				end
			end
			
			public.execute = function()
				com.splosive.trace("Set > execute > property = " .. this.context.descriptor.property , "View-property-Set")
				if(this.context.target == this.context.currentView)then
					if(this.context.descriptor.property == "isVisible")then
						this.context.target.setVisible(this.context.descriptor.value)
					else
						this.context.target[this.context.descriptor.property] = this.context.descriptor.value
					end
				else
					this.context.target[this.context.descriptor.property] = this.context.descriptor.value
				end
				
				super.public.execute()
			end
			
			
			return api
			
		end
		
		--[[
		================================================
		EQ is a simple action that compares a property with a value, it can be nested in another behavior to set a property when a specific trigger occurs
		================================================
		]]
	
		local EQ = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			public.execute = function()
				if(this.context.target[this.context.descriptor.property] == this.context.descriptor.value) then
					super.public.execute()
				end
			end
			
			
			return api
			
		end
	
		package.EQ = EQ
		package.Toggle = Toggle
		package.Set = Set
		package.watchGT = watchGT
		
		
		return package
	
	
	end
	
--[[
	================================================
	script package: Contains behaviors that interact with Lua script
	================================================
	]]
	
	local script = function()
		
		local package = {}
	
		--[[
		================================================
		Call executes an action when a property is Greater Than a targetValue
		================================================
		]]
	
		local Call = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			
			public.activate = function()
				com.splosive.trace("call > activate", "View-Behavior-Call")
				
				if(this.context.params == nil)then
					this.context.params = {}
				end
				
				if(this.context.event == "OBJECT_PRESS" or this.context.event == "OBJECT_RELEASE")then
					--this.context.eventSource.touch = this.objectPressed
					this.context.eventSource:addEventListener( "touch", this.objectPressed )
				end
				super.public.activate()
			end
			
			public.deactivate = function()
				com.splosive.trace("call > deactivate", "View-Behavior-Call")
				if(this.context.eventSource ~= nil)then
					--this.context.eventSource.touch = nil
					this.context.eventSource:removeEventListener( "touch", this.objectPressed)
				end
				super.public.deactivate()
			end
			
			protected.objectPressed = function(event)
				if(event.phase == "began" and this.context.event == "OBJECT_PRESS") then
					public.execute()
				elseif(event.phase == "ended" and this.context.event == "OBJECT_RELEASE") then
					public.execute()
				end
				
				return true
				
			end
			
			public.execute = function()
				com.splosive.trace("call > execute", "View-Behavior-Call")
				this.context.currentView[this.context.descriptor.method](this.context.params)
				super.public.execute()
			end
			
			
			return api
			
		end
		
	
		package.Call = Call
		
		
		return package
	
	
	end
	
	
--[[
	================================================
	collectible
	================================================
	]]
	
	local collectible = function()
		
		local package = {}
	
		
		--[[
		================================================
		PointsToken, when the eventSource (s) is/are collided by the target it awards the player points and removes such eventSource from the view
		================================================
		]]
	
		local PointsToken = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			protected.collidedSource = nil
			protected.soundObj = nil
			
			public.activate = function()
				com.splosive.trace("PointsToken > activate ", "View-Behavior-PointsToken")
			
				if(this.context.eventSources ~= nil)then
					com.splosive.trace("PointsToken > this.context.descriptor.eventSources = " .. this.context.descriptor.eventSources, "View-Behavior-PointsToken")
					for k,v in pairs(this.context.eventSources) do
						com.splosive.trace("adding listenr to eventSource = " .. v.id, "View-Behavior-PointsToken")
						v.collision = this.objectCollision
						v:addEventListener( "collision", v )
					end
				elseif(this.context.eventSource ~= nil)then
					com.splosive.trace("PointsToken > activate = this.context.eventSource = " .. this.context.descriptor.eventSource, "View-Behavior-PointsToken")
					this.context.eventSource.collision = this.objectCollision
					this.context.eventSource:addEventListener( "collision",  this.context.eventSource)
				end
				
				
				if(this.context.descriptor.sound ~= nil)then
					this.soundObj = audio.loadSound( this.context.descriptor.sound )
				end
				
				super.public.activate()
				
			end
			
			public.deactivate = function()
				com.splosive.trace("PointsToken > deactivate ", "View-Behavior-PointsToken")
				if(this.context.eventSources ~= nil)then
					com.splosive.trace("PointsToken > this.context.descriptor.eventSources = " .. this.context.descriptor.eventSources, "View-Behavior-PointsToken")
					for k,v in pairs(this.context.eventSources) do
						com.splosive.trace("removing listener from eventSource = " .. v.id, "View-Behavior-PointsToken")
						v.collision = nil
						v:removeEventListener( "collision", v )
					end
				elseif(this.context.eventSource ~= nil)then
					com.splosive.trace("PointsToken > deactivate = this.context.eventSource = " .. this.context.descriptor.eventSource, "View-Behavior-PointsToken")
					this.context.eventSource.collision = nil
					this.context.eventSource:removeEventListener( "collision", this.context.eventSource )
				end
				super.public.deactivate()
				
			end
			
			protected.objectCollision = function(self, event)
				if(this.context.target ~= nil)then
					if(event.other == this.context.target) then
						this.collidedSource = self
						timer.performWithDelay( 50, public.execute )
					end
				elseif(this.context.targets ~= nil)then
					for k,v in ipairs(this.context.targets) do
						if(event.other == v) then
							this.collidedSource = self
							timer.performWithDelay( 50, public.execute )
						end				
					end
				end
			end
			
			public.execute = function()
				com.splosive.trace("PointsToken > execute", "View-Behavior-PointsToken")
				--this.collidedSource.collision = nil
				--this.collidedSource:removeEventListener( "collision", this.collidedSource )
				this.context.currentView.removeObject( this.collidedSource )
				
				--[[
				if(this.context.eventSources ~= nil)then
					com.splosive.trace("eventSources are not nil!", "View-Behavior-PointsToken")
					for k,v in pairs(this.context.eventSources) do
						com.splosive.trace("Comparing item " .. k , "View-Behavior-PointsToken")
						if(v == this.collidedSource)then
							com.splosive.trace("Removing item " .. k .. " from context", "View-Behavior-PointsToken")
							this.context.eventSources[k] = nil
						end
					end
				elseif(this.context.eventSource ~= nil)then
					this.context.eventSource = nil
				end
				]]
				
				com.splosive.trace("give points!", "View-Behavior-PointsToken")
				if(this.soundObj ~= nil)then
					audio.play( this.soundObj )
				end
				super.public.execute()
			end
			
			
			return api
			
		end
		
		package.PointsToken = PointsToken
		
		return package
	
	
	end
	
	
--[[
	================================================
	media
	================================================
	]]
	
	local media = function()
		
		local package = {}
	
		
		--[[
		================================================
		PlaySound
		================================================
		]]
	
		local PlaySound = function(context)
		
			local public = {}
			local protected = {}
			
			local super = templates.BehaviorTemplate(context, public, protected)
			-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
			-- it will go up to the base class
			local this = protected
			-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
			local api = public
			
			protected.collidedSource = nil
			protected.soundObj = nil
			
			public.activate = function()
				com.splosive.trace("PlaySound > activate ", "View-Behavior-PlaySound")
				if(this.context.descriptor.sound ~= nil)then
					com.splosive.trace("preload sound > " .. this.context.descriptor.sound, "View-Behavior-PlaySound")
					this.soundObj = audio.loadSound( this.context.descriptor.sound )
				end
				
				super.public.activate()
				
			end
			
			public.deactivate = function()
				com.splosive.trace("PlaySound > deactivate ", "View-Behavior-PlaySound")
				super.public.deactivate()
				
			end
			
			public.execute = function()
				com.splosive.trace("PlaySound > execute", "View-Behavior-PlaySound")
				
				
				if(this.soundObj ~= nil)then
					audio.play( this.soundObj )
				end
				super.public.execute()
			end
			
			
			return api
			
		end
		
		package.PlaySound = PlaySound
		
		return package
	
	
	end


	local behaviors = {}
	
	
	behaviors.utils = utils()
	behaviors.physics = physics()
	behaviors.camera = camera()
	behaviors.interactive = interactive()
	behaviors.sprite = sprite()
	behaviors.view = view()
	behaviors.property = property()
	behaviors.script = script()
	behaviors.collectible = collectible()
	behaviors.media = media()
	
	
	
	
	package.behaviors = behaviors
	
	
	return package

end

	
